package com.ldatum.crm.daoImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.ldatum.crm.dao.ToDoItemDao;
import com.ldatum.crm.domain.ToDoItem;
import com.ldatum.crm.util.HibernateUtil;

public class ToDoItemDaoImpl implements ToDoItemDao {

	@Override
	public ToDoItem findById(int id) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			return (ToDoItem) s.get(ToDoItem.class, id);
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public List<ToDoItem> list(Class<ToDoItem> class1, String creater) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from ToDoItem as toDoItem where follower like :follower order by status desc,remindTime desc";
			Query q = s.createQuery(hql);
			q.setString("follower", creater);
			@SuppressWarnings("unchecked")
			List<ToDoItem> list = (List<ToDoItem>) q.list();
			return list;
		}finally{
			if(s!=null){
				s.close();
			}
		}
	}

	@Override
	public void delete(int id) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			ToDoItem tdi = new ToDoItem();
			tdi.setId(id);
			s.delete(tdi);
			tx.commit();
		}finally{
			if(s!=null)
			s.close();
		}
	}

	@Override
	public void save(ToDoItem toDoItem) {
		HibernateUtil.add(toDoItem);
	}

	@Override
	public void update(ToDoItem toDoItem) {
		HibernateUtil.update(toDoItem);
	}

	@Override
	public List<ToDoItem> findUnFinished(String fullname) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from ToDoItem as toDoItem where follower like :follower and status = '未完成' order by status desc,remindTime desc";
			Query q = s.createQuery(hql);
			q.setString("follower", fullname);
			@SuppressWarnings("unchecked")
			List<ToDoItem> list = (List<ToDoItem>) q.list();
			return list;
		}finally{
			if(s!=null){
				s.close();
			}
		}
	}

}
